package com.dfs.parent.common.web.handle;

import com.dfs.parent.common.core.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GlobalExceptionHandler
 * @Author hong
 * @Date 2019/9/21 2:19 PM
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * HTTP 请求 → DispatcherServlet → HandlerMapping → 找不到 Controller → 抛出 NoHandlerFoundException
     *                                                                  |
     *                                                                  ↓
     *                                                       进入 Spring 的底层异常处理机制
     *                                                                  |
     *                                                                  ↓
     *                                             默认行为：返回 404 + Whitelabel Error Page（HTML）
     * @param ex
     * @param req
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handle404(NoHandlerFoundException ex, HttpServletRequest req) {
        return Result.fail("接口不存在: " + ex.getRequestURL());
    }
    @ExceptionHandler(Exception.class)
    public Result baseExceptionHandler(HttpServletRequest req, Exception ex) {
        log.error(req.getRequestURI(),ex);
        return Result.fail(ex.getMessage());
    }

}
